<?php

namespace app\api\controller\master;

use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use think\Cache;


/**
 * 用户端公共接口
 */
class Common extends Controller
{

    protected static $user;

    public function _initialize()
    {
        header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
        //self::$user = $this->check_authority();
    }


    /**
     * @param array $data
     * @return array
     * $data=['id','name'=>'123']  id必填，name选填，默认值为123（有默认值时key不能为int）
     */
    public function post(array $data)
    {
        if (empty($data)) {
            r_date([], 300, '提交数据不正确');
        }
        $return = [];
        foreach ($data as $key => $item) {
            if (!is_int($key)) {
                $val = Request::instance()->post($key);
                if (isset($val)) {
                    $return[$key] = trim($val);
                } else {
                    $return[$key] = trim($item);
                }
            } else {
                $val = Request::instance()->post($item);
                if (!isset($val)) {
                    jso_data([], 300, "缺少 $item 数据");
                }
                $return[$item] = trim($val);
            }
        }
        return $return;
    }

    /**
     * 检测用户登录和权限
     */
    public function check_authority()
    {
        $access_token = Request::instance()->header("access-token");
        $access_token = empty($access_token) ? input("post.access_token") : $access_token;

        if (empty($access_token)) {
            jso_data([], 401, '您还未登录账号，请先登录');
        }
        $user = db('user')->where(['access_token' => $access_token])->find();

        if (empty($user)) {
            jso_data([], 401, '账号已下线，请重新登录');
        }
        if ($user['status'] == 1) {
            jso_data([], 300, '请等待审核');
        }
        if ($user['status'] == 3) {
            jso_data([], 300, '该用户已冻结');
        }
        return $user;
    }



    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 师傅端沟通记录
     */
    public function gou()
    {
        $data = Request::instance()->param();
        $re=db('through')
                ->insertGetId([
                    'mode' => "其它",
                    'amount' =>0,
                    'role' =>$data['role'],
                    'remar' => $data['remar'],
                    'order_ids' => $data['order_ids'],
                    'baocun' => 0,
                    'gid' => $data['gid'],
                    'th_time' => $data['th_time']
                ]);

        if($re){
            jso_data([], 200, '新增成功');
        }
        jso_data([], 300);

        }
    /*
     * 查看沟通记录
     */
        public function cha(){

        $data  = $this->post(['page' => 1, 'limit' => 10, 'order_id','role','gid']);

        $us=db('through')->field('remar,role,th_time,order_ids,url,log,gid');
            if(!empty($data['role'])){
                $us->where('role',$data['role']);
            }
            if(!empty($data['gid'])){
                $us->where('gid',$data['gid']);
            }
            $l=$us->where('order_ids',$data['order_id'])
            ->page($data['page'], $data['limit'])
            ->select();

        foreach ($l as $k=>$v){

            if($v['url']){

                $l[$k]['url'] = unserialize($v['url']);
            }else{
                $l[$k]['url']='';
            }
            if($v['log']){
                $l[$k]['log'] = unserialize($v['log']);
            }else{
                $l[$k]['log']='';
            }
        }


            jso_data($l, 200);
    }
    /*
     * 查看付款详情
     */
    public function Receivables(){

        $data  = $this->post(['type','order_no']);

        if($data['type']==1){
            $o=db('recharge')->where(['order_no'=>$data['order_no'],'project'=>2,'status'=>1])->find();
            if($o){
              $l['state']=1;
          }else{
              $l['state']=2;
          }
        }elseif ($data['type']==2){
            $o=db('recharge')->where(['order_no'=>$data['order_no'],'project'=>3,'status'=>1])->find();
            if($o){
                $l['state']=1;
            }else{
                $l['state']=2;
            }
        }

        jso_data($l, 200);
    }
    /*
    * 订单完成后返工
    */
    public function rework(){

        $data  = $this->post(['order_no']);
        $o = db('order')->where(['order_no' => $data['order_no'], 'state' => 7, 'rework' => 1])->find();
        if($o) {
            db('order')->where(['order_no' => $data['order_no'], 'state' => 7, 'rework' => 1])->update(['rework'=>0]);
            jso_data([], 200);
        }

        jso_data([], 300,'订单不存在');
    }
    /*
    * 订单完工
    */
    public function finished(){

        $data  = $this->post(['order_id']);
        $o=db('order')->where(['order_id' => $data['order_id']])->update(['state' => 7, 'update_time' => time()]);
        if($o) {
            jso_data([], 200);
        }
        jso_data([], 300,'订单不存在');
    }
    /*
    * 根据店铺查店长
    */
    public function shop(){

        $data  = $this->post(['store_id']);

        $l=db('user')
            ->field('user.user_id,user.username,user.mobile,st.store_name')
            ->join('store st','user.store_id=st.store_id','left')
            ->where('user.store_id',$data['store_id'])
            ->select();

        jso_data($l, 200);
    }

    /**
     * 店铺详情
     * invoice_type
     */
    public function xiang_q(){
        $P= Request::instance()->post('store_id');
        $res=db('store')
            ->field('store.store_name,store.addres,pe.province,ci.city,cu.county')
            ->join('province pe','pe.province_id=store.province','left')
            ->join('city ci','ci.city_id=store.city','left')
            ->join('county cu','cu.county_id=store.area','left')
            ->where('store_id',$P)
            ->find();
        if($res!==false){
            jso_data($res,200);
        }
        jso_data([],300);


    }
     /**
     * 完工时间
     */
    public function Commencement()
    {
        $data  = $this->post(['order_id']);
        $startup = db('startup')->where('orders_id',$data['order_id'])->find();
        if(empty($startup['sta_time']) && empty($startup['up_time'])){
            $thro = db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->order('th_time desc')->find();
            if ($thro) {
                $ca = db('envelopes')->where(['through_id' => $thro['through_id']])->field('gong')->find();
            } else {
                $ca = db('envelopes')->where(['ordesr_id' => $data['order_id']])->field('gong')->find();
            }
            $da=['sta_time' => time(), 'up_time' => strtotime("+".$ca['gong']."day", time())];
            $res = db('startup')->where('orders_id',$data['order_id'])->update($da);
            if ($res) {
                jso_data($da, 200);
            } else {
                jso_data([], 300);
            }
        }
        jso_data([], 200);


    }
    /**
     * 店铺
     * invoice_type
     */
    public function dian(){
        $res=db('store')->select();
        if($res!==false){
            jso_data($res,200);
        }
        jso_data([],300,'编辑失败，请刷新后重试');


    }
    /**
     * 店铺
     * invoice_type
     */
    public function pu(){
        $res=db('store')->select();
        if($res!==false){
            r_date($res,200);
        }
        r_date([],300,'编辑失败，请刷新后重试');


    }
    /** ****************************************************************************统计接***************************************************************/
    public function ss()
    {

        $this->_initialize();

        if (Cache::has('tongji')) {
            $ui = Cache::get('tongji');
        } else {
            $ui = db('tongji')->select();
            Cache::set('tongji', $ui);
        }

        r_date($ui);
    }
    //将excel数据插入数据库

    public function insertExcelArray()
    {
        vendor("phpoffice.phpexcel.Classes.PHPExcel");
        $PHPExcel = new \PHPExcel();                                 // 创建PHPExcel对象，注意，不能少了\

        $file = request()->file('file');

        if ($file) {
            $info = $file->validate(['ext' => 'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'uploads/Excel');
            if ($info) {


                $exclePath = $info->getSaveName();  //获取文件名
                $file_name = ROOT_PATH . 'public' . DS . 'uploads/Excel' . DS . $exclePath;   //上传文件的地址

                //截取文件后缀 xlsx xls
                $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                //区分上传文件格式
                if ($extension == 'xlsx') {
                    $objReader    = \PHPExcel_IOFactory::createReader('Excel2007');
                    $obj_PHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                } else if ($extension == 'xls') {
                    $objReader    = \PHPExcel_IOFactory::createReader('Excel5');
                    $obj_PHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                }
                $excel_array = $obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
                array_shift($excel_array);  //删除第一个数组(标题);

                $data = [];
                foreach ($excel_array as $k => $v) {

                    $data[$k]['chengshi']  = $v[0];
                    $data[$k]['quyu']      = $v[1];
                    $data[$k]['qianyue']   = strtotime($v[2]);
                    $data[$k]['jinchang']  = $v[3];
                    $data[$k]['hetong']    = $v[4];
                    $data[$k]['laiyuan']   = $v[5];
                    $data[$k]['beizhu']    = $v[6];
                    $data[$k]['dingdan']   = $v[7];
                    $data[$k]['xingming']  = $v[8];
                    $data[$k]['dianhua']   = $v[9];
                    $data[$k]['dizhi']     = $v[10];
                    $data[$k]['leibie']    = $v[11];
                    $data[$k]['erji']      = $v[12];
                    $data[$k]['sanji']     = $v[13];
                    $data[$k]['bianhao']   = $v[14];
                    $data[$k]['shijian']   = $v[15];
                    $data[$k]['chengjiao'] = $v[16];
                    $data[$k]['tianshu']   = $v[17];
                    $data[$k]['beizhu1']   = $v[18];
                    $data[$k]['jiedan']    = $v[19];
                    $data[$k]['EMPTY_2']   = $v[20];
                    $data[$k]['EMPTY_3']   = $v[21];
                    $data[$k]['EMPTY_4']   = $v[22];
                    $data[$k]['EMPTY_5']   = $v[23];
                }
                db('tongji')->insertAll($data);
                Cache::set('tongji', $data);
                r_date(Cache::get('tongji'), 200);
            } else {
                r_date([], 300, '错误');
            }
        } else {
            r_date([], 300, '请上传文件');

        }

    }

    public function insertExcelArrasy()
    {

        vendor("phpoffice.phpexcel.Classes.PHPExcel");
        $PHPExcel = new \PHPExcel();                                 // 创建PHPExcel对象，注意，不能少了\
        $file     = request()->file('files');

        if ($file) {
            $info = $file->validate(['ext' => 'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'uploads/Excel');

            if ($info) {


                $exclePath = $info->getSaveName();  //获取文件名
                $file_name = ROOT_PATH . 'public' . DS . 'uploads/Excel' . DS . $exclePath;   //上传文件的地址

                //截取文件后缀 xlsx xls
                $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                //区分上传文件格式

                if ($extension == 'xlsx') {
                    $objReader    = \PHPExcel_IOFactory::createReader('Excel2007');
                    $obj_PHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                } else if ($extension == 'xls') {
                    $objReader    = \PHPExcel_IOFactory::createReader('Excel5');
                    $obj_PHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                }
                $excel_array = $obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
                array_shift($excel_array);  //删除第一个数组(标题);

                $data = [];

                foreach ($excel_array as $k => $v) {
                    $data[$k]['riqi']          = strtotime($v[0]);
                    $data[$k]['chengshi']      = $v[1];
                    $data[$k]['quyu']          = $v[2];
                    $data[$k]['laiyuan']       = $v[3];
                    $data[$k]['qudao']         = $v[4];
                    $data[$k]['beizhu']        = $v[5];
                    $data[$k]['dingdan']       = $v[6];
                    $data[$k]['kefu']          = $v[7];
                    $data[$k]['jiedanshjian']  = $v[8];
                    $data[$k]['paidanshijian'] = $v[9];
                    $data[$k]['xingming']      = $v[10];
                    $data[$k]['dianhua']       = $v[11];
                    $data[$k]['dizhi']         = $v[12];
                    $data[$k]['leibie']        = $v[13];
                    $data[$k]['erji']          = $v[14];
                    $data[$k]['sanji']         = $v[15];

                    $data[$k]['yixiang']  = $v[16];
                    $data[$k]['baojia']   = $v[17];
                    $data[$k]['youxiao']  = $v[18];
                    $data[$k]['jiedan']   = $v[19];
                    $data[$k]['fankui']   = $v[20];
                    $data[$k]['shangmen'] = $v[21];
                    $data[$k]['shiji']    = $v[22];

                    $data[$k]['jiance']          = $v[23];
                    $data[$k]['jianceerji']      = $v[24];
                    $data[$k]['jiancesanji']     = $v[25];
                    $data[$k]['chengjiashijian'] = $v[26];
                    $data[$k]['chengjiaojiee']   = $v[27];
                }
                db('baobiao')->insertAll($data);
                Cache::set('baobiao', $data);

                r_date(Cache::get('baobiao'), 200);
            } else {
                r_date([], 300, '错误');
            }
        } else {
            r_date([], 300, '请上传文件');
        }

    }

    public function oo()
    {

        $data = Request::instance()->post();
        $u    = db('baobiao');
        if (isset($data['qudao']) && $data['qudao'] != '') {
            $u->where(['laiyuan' => $data['qudao']]);
        }
        if (isset($data['leibie']) && $data['leibie'] != '') {
            $u->where(['leibie' => $data['leibie']]);
        }
        $i = $u->where(['baobiao.youxiao' => '是'])->select();
        foreach ($i as $k => $o) {
            $i[$k]['riqi']      = date('Y-m-d', $o['riqi']);
            $i[$k]['chengjiao'] = db('tongji')->where(['dianhua' => $o['dianhua']])->sum('chengjiao');
        }
            r_date($i,200);

    }

    public function oo1()
    {
        $data = Request::instance()->post();

            $u1    = db('baobiao')->where('leibie',$data['leibies'])->field('erji')->select();



            r_date($u1, 200);

    }
}
